// 消消乐游戏类
class Match3Game {
    constructor() {
        this.canvas = document.getElementById('match3-canvas');
        this.ctx = this.canvas.getContext('2d');
        
        this.BOARD_SIZE = 8;
        this.CELL_SIZE = 60;
        this.COLORS = ['#FF6B6B', '#4ECDC4', '#45B7D1', '#96CEB4', '#FFEAA7', '#DDA0DD', '#98D8C8'];
        
        this.board = [];
        this.selectedCell = null;
        this.score = 0;
        this.targetScore = 1000;
        this.movesLeft = 30;
        this.isGameRunning = false;
        this.animating = false;
        
        this.bindEvents();
        this.loadAndDisplayGameData();
    }

    // 初始化游戏板
    initBoard() {
        this.board = [];
        for (let row = 0; row < this.BOARD_SIZE; row++) {
            this.board[row] = [];
            for (let col = 0; col < this.BOARD_SIZE; col++) {
                this.board[row][col] = Math.floor(Math.random() * this.COLORS.length);
            }
        }
        
        // 确保初始状态没有匹配
        this.removeInitialMatches();
    }

    // 移除初始匹配
    removeInitialMatches() {
        let hasMatches = true;
        while (hasMatches) {
            hasMatches = false;
            for (let row = 0; row < this.BOARD_SIZE; row++) {
                for (let col = 0; col < this.BOARD_SIZE; col++) {
                    if (this.hasMatchAt(row, col)) {
                        this.board[row][col] = Math.floor(Math.random() * this.COLORS.length);
                        hasMatches = true;
                    }
                }
            }
        }
    }

    // 检查指定位置是否有匹配
    hasMatchAt(row, col) {
        const color = this.board[row][col];
        
        // 检查水平匹配
        let horizontalCount = 1;
        // 向左检查
        for (let c = col - 1; c >= 0 && this.board[row][c] === color; c--) {
            horizontalCount++;
        }
        // 向右检查
        for (let c = col + 1; c < this.BOARD_SIZE && this.board[row][c] === color; c++) {
            horizontalCount++;
        }
        
        // 检查垂直匹配
        let verticalCount = 1;
        // 向上检查
        for (let r = row - 1; r >= 0 && this.board[r][col] === color; r--) {
            verticalCount++;
        }
        // 向下检查
        for (let r = row + 1; r < this.BOARD_SIZE && this.board[r][col] === color; r++) {
            verticalCount++;
        }
        
        return horizontalCount >= 3 || verticalCount >= 3;
    }

    // 开始游戏
    async startGame() {
        this.initBoard();
        this.score = 0;
        this.movesLeft = 30;
        this.targetScore = 1000;
        this.selectedCell = null;
        this.isGameRunning = true;
        this.updateScore();
        await this.updateGameStats();
        this.draw();
    }

    // 重新开始游戏
    restartGame() {
        this.startGame();
    }

    // 绑定事件
    bindEvents() {
        this.canvas.addEventListener('click', (e) => {
            if (!this.isGameRunning || this.animating) return;
            
            const rect = this.canvas.getBoundingClientRect();
            const x = e.clientX - rect.left;
            const y = e.clientY - rect.top;
            
            const col = Math.floor(x / this.CELL_SIZE);
            const row = Math.floor(y / this.CELL_SIZE);
            
            if (row >= 0 && row < this.BOARD_SIZE && col >= 0 && col < this.BOARD_SIZE) {
                this.handleCellClick(row, col);
            }
        });
    }

    // 处理单元格点击
    handleCellClick(row, col) {
        if (!this.selectedCell) {
            // 选择第一个单元格
            this.selectedCell = { row, col };
            this.draw();
        } else {
            // 检查是否点击同一个单元格
            if (this.selectedCell.row === row && this.selectedCell.col === col) {
                this.selectedCell = null;
                this.draw();
                return;
            }
            
            // 检查是否相邻
            const isAdjacent = Math.abs(this.selectedCell.row - row) + Math.abs(this.selectedCell.col - col) === 1;
            
            if (isAdjacent) {
                // 尝试交换
                this.trySwap(this.selectedCell.row, this.selectedCell.col, row, col);
            }
            
            this.selectedCell = null;
            this.draw();
        }
    }

    // 尝试交换两个单元格
    async trySwap(row1, col1, row2, col2) {
        // 交换
        const temp = this.board[row1][col1];
        this.board[row1][col1] = this.board[row2][col2];
        this.board[row2][col2] = temp;
        
        this.draw();
        await this.sleep(200);
        
        // 检查是否产生匹配
        const matches = this.findMatches();
        
        if (matches.length > 0) {
            // 有效交换
            this.movesLeft--;
            this.updateScore();
            await this.processMatches();
            this.checkGameEnd();
        } else {
            // 无效交换，恢复原状
            const temp2 = this.board[row1][col1];
            this.board[row1][col1] = this.board[row2][col2];
            this.board[row2][col2] = temp2;
            this.draw();
        }
    }

    // 处理匹配
    async processMatches() {
        this.animating = true;
        
        while (true) {
            const matches = this.findMatches();
            if (matches.length === 0) break;
            
            // 计算分数
            this.score += matches.length * 10;
            
            // 移除匹配的宝石
            matches.forEach(({ row, col }) => {
                this.board[row][col] = -1; // 标记为空
            });
            
            this.draw();
            await this.sleep(300);
            
            // 下落
            this.dropGems();
            this.draw();
            await this.sleep(300);
            
            // 填充新宝石
            this.fillBoard();
            this.draw();
            await this.sleep(300);
        }
        
        this.animating = false;
        this.updateScore();
        await this.saveGameData();
    }

    // 查找所有匹配
    findMatches() {
        const matches = [];
        const visited = Array(this.BOARD_SIZE).fill().map(() => Array(this.BOARD_SIZE).fill(false));
        
        for (let row = 0; row < this.BOARD_SIZE; row++) {
            for (let col = 0; col < this.BOARD_SIZE; col++) {
                if (!visited[row][col] && this.board[row][col] !== -1) {
                    const matchGroup = this.getMatchGroup(row, col, visited);
                    if (matchGroup.length >= 3) {
                        matches.push(...matchGroup);
                    }
                }
            }
        }
        
        return matches;
    }

    // 获取匹配组
    getMatchGroup(startRow, startCol, visited) {
        if (visited[startRow][startCol]) return [];
        
        const color = this.board[startRow][startCol];
        if (color === -1) return [];
        
        const group = [];
        
        // 水平匹配
        const horizontalGroup = [{ row: startRow, col: startCol }];
        // 向左
        for (let col = startCol - 1; col >= 0 && this.board[startRow][col] === color; col--) {
            horizontalGroup.unshift({ row: startRow, col });
        }
        // 向右
        for (let col = startCol + 1; col < this.BOARD_SIZE && this.board[startRow][col] === color; col++) {
            horizontalGroup.push({ row: startRow, col });
        }
        
        if (horizontalGroup.length >= 3) {
            group.push(...horizontalGroup);
        }
        
        // 垂直匹配
        const verticalGroup = [{ row: startRow, col: startCol }];
        // 向上
        for (let row = startRow - 1; row >= 0 && this.board[row][startCol] === color; row--) {
            verticalGroup.unshift({ row, col: startCol });
        }
        // 向下
        for (let row = startRow + 1; row < this.BOARD_SIZE && this.board[row][startCol] === color; row++) {
            verticalGroup.push({ row, col: startCol });
        }
        
        if (verticalGroup.length >= 3) {
            group.push(...verticalGroup);
        }
        
        // 去重并标记为已访问
        const uniqueGroup = [];
        const seen = new Set();
        group.forEach(({ row, col }) => {
            const key = `${row},${col}`;
            if (!seen.has(key)) {
                seen.add(key);
                uniqueGroup.push({ row, col });
                visited[row][col] = true;
            }
        });
        
        return uniqueGroup;
    }

    // 宝石下落
    dropGems() {
        for (let col = 0; col < this.BOARD_SIZE; col++) {
            let writePos = this.BOARD_SIZE - 1;
            for (let row = this.BOARD_SIZE - 1; row >= 0; row--) {
                if (this.board[row][col] !== -1) {
                    this.board[writePos][col] = this.board[row][col];
                    if (writePos !== row) {
                        this.board[row][col] = -1;
                    }
                    writePos--;
                }
            }
        }
    }

    // 填充新宝石
    fillBoard() {
        for (let row = 0; row < this.BOARD_SIZE; row++) {
            for (let col = 0; col < this.BOARD_SIZE; col++) {
                if (this.board[row][col] === -1) {
                    this.board[row][col] = Math.floor(Math.random() * this.COLORS.length);
                }
            }
        }
    }

    // 检查游戏结束
    checkGameEnd() {
        if (this.score >= this.targetScore) {
            this.isGameRunning = false;
            setTimeout(() => {
                alert(`恭喜！你达到了目标分数！\n得分: ${this.score}\n剩余步数: ${this.movesLeft}`);
            }, 500);
        } else if (this.movesLeft <= 0) {
            this.isGameRunning = false;
            setTimeout(() => {
                alert(`游戏结束！\n得分: ${this.score}\n目标分数: ${this.targetScore}`);
            }, 500);
        }
    }

    // 绘制游戏
    draw() {
        // 清空画布
        this.ctx.fillStyle = '#2C3E50';
        this.ctx.fillRect(0, 0, this.canvas.width, this.canvas.height);
        
        // 绘制网格
        for (let row = 0; row < this.BOARD_SIZE; row++) {
            for (let col = 0; col < this.BOARD_SIZE; col++) {
                const x = col * this.CELL_SIZE;
                const y = row * this.CELL_SIZE;
                
                // 绘制背景
                this.ctx.fillStyle = '#34495E';
                this.ctx.fillRect(x + 2, y + 2, this.CELL_SIZE - 4, this.CELL_SIZE - 4);
                
                // 绘制宝石
                if (this.board[row][col] !== -1) {
                    this.ctx.fillStyle = this.COLORS[this.board[row][col]];
                    this.ctx.beginPath();
                    this.ctx.arc(x + this.CELL_SIZE / 2, y + this.CELL_SIZE / 2, this.CELL_SIZE / 2 - 8, 0, Math.PI * 2);
                    this.ctx.fill();
                    
                    // 添加高光效果
                    this.ctx.fillStyle = 'rgba(255, 255, 255, 0.3)';
                    this.ctx.beginPath();
                    this.ctx.arc(x + this.CELL_SIZE / 2 - 8, y + this.CELL_SIZE / 2 - 8, this.CELL_SIZE / 6, 0, Math.PI * 2);
                    this.ctx.fill();
                }
                
                // 绘制选中效果
                if (this.selectedCell && this.selectedCell.row === row && this.selectedCell.col === col) {
                    this.ctx.strokeStyle = '#F39C12';
                    this.ctx.lineWidth = 4;
                    this.ctx.strokeRect(x + 2, y + 2, this.CELL_SIZE - 4, this.CELL_SIZE - 4);
                }
            }
        }
    }

    // 更新分数显示
    updateScore() {
        document.getElementById('match3-score').textContent = this.score;
        document.getElementById('target-score').textContent = this.targetScore;
        document.getElementById('moves-left').textContent = this.movesLeft;
    }

    // 睡眠函数
    sleep(ms) {
        return new Promise(resolve => setTimeout(resolve, ms));
    }

    // 保存游戏数据
    async saveGameData() {
        const currentData = await this.loadGameData();
        const gameData = {
            highScore: Math.max(this.score, currentData.highScore || 0),
            lastScore: this.score,
            gamesPlayed: (currentData.gamesPlayed || 0) + (this.isGameRunning ? 0 : 1)
        };
        await authManager.saveGameData('match3', gameData);
    }

    // 加载游戏数据
    async loadGameData() {
        return await authManager.loadGameData('match3') || { highScore: 0 };
    }

    // 更新游戏统计显示
    async updateGameStats() {
        const data = await this.loadGameData();
        document.getElementById('match3-high-score').textContent = data.highScore || 0;
    }

    // 加载并显示游戏数据
    async loadAndDisplayGameData() {
        await this.updateGameStats();
    }
}

// 创建游戏实例
let match3Game;